import {
  getCateParamsReq,
  addOrEditParamsReq,
  deleteParamsReq,
  queryParamsValReq,
} from '../request/params'
import { getGoodsCateListReq } from '../request/goods-cate'
const actions = {
  // 获取分类参数
  async getCateParams(context, { id, sel }) {
    const cateParamsData = await getCateParamsReq(id, { sel })
    if (sel === 'many') {
      // 动态参数
      cateParamsData.forEach(
        item => (item.attr_vals = item.attr_vals.split(','))
      )
      context.commit('GET_CATE_PARAMS', { type: 'many', cateParamsData })
    } else {
      // 静态参数
      context.commit('GET_CATE_PARAMS', { type: 'only', cateParamsData })
    }
  },
  // 获取商品分类
  async getGoodsCateList(context) {
    try {
      const goodsCateListData = await getGoodsCateListReq()
      context.commit('GET_GOODS_CATE_LIST', goodsCateListData)
    } catch (error) {
      console.log(error)
    }
  },
  // 添加或编辑参数（动静）
  async addOrEditParams(context, { id, params, attrId }) {
    try {
      const addOrEditParamsData = await addOrEditParamsReq(id, params, attrId)
      return addOrEditParamsData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 删除参数
  async deleteParams(context, { id, attrid }) {
    try {
      return await deleteParamsReq(id, attrid)
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 根据参数id查询参数值
  async queryParamsVal(context, { id, attrId, params }) {
    try {
      return await queryParamsValReq(id, attrId, params)
    } catch (error) {
      return Promise.reject(error)
    }
  },
}

const mutations = {
  GET_CATE_PARAMS(state, { type, cateParamsData }) {
    type === 'many'
      ? (state.manyParamsList = cateParamsData)
      : (state.onlyParamsList = cateParamsData)
  },
  GET_GOODS_CATE_LIST(state, goodsCateListData) {
    state.goodsCateList = goodsCateListData
  },
}
const state = {
  manyParamsList: [], // 动态参数
  onlyParamsList: [], // 静态参数
  goodsCateList: [], // 商品分类列表
}
const getters = {}

export default {
  namespaced: true,
  actions,
  mutations,
  state,
  getters,
}
